package io.gitee.yth.design.pattern.test.core.pattern.behavioral.strategy;

import io.gitee.yth.design.pattern.test.core.pattern.behavioral.strategy.cache.KeyValueCache;
import io.gitee.yth.design.pattern.test.core.pattern.behavioral.strategy.serializer.JacksonSerializer;
import io.gitee.yth.design.pattern.test.core.pattern.behavioral.strategy.serializer.SerializeStrategy;

/**
 * @author yth
 * @since 2023-05-03-14:49
 */
public class CacheManager<K, V> {

    private final KeyValueCache<String, String> cache;
    private SerializeStrategy serializer = new JacksonSerializer();

    public CacheManager(KeyValueCache<String, String> cache) {
        this.cache = cache;
    }

    public CacheManager(KeyValueCache<String, String> cache, SerializeStrategy serializeStrategy) {
        this.cache = cache;
        this.serializer = serializeStrategy;
    }

    public void putCache(K key, V value) {
        final String serialKey = serializer.serialize(key);
        final String serialVal = serializer.serialize(value);
        cache.put(serialKey, serialVal);
    }

    public void evictCache(K key) {
        final String serialKey = serializer.serialize(key);
        cache.remove(serialKey);
    }

    public V getCache(K key, Class<V> clazz) {
        final String serialKey = serializer.serialize(key);
        final String value = cache.get(serialKey);
        return serializer.deserialize(value, clazz);
    }

}
